<template>
  <div>
    <el-upload class="upload-demo"
               accept="image/jpeg,image/gif,image/png"
               multiple
               :show-file-list="false"
               :action="conf.imgUrl"
               :limit="limitText"
               :beforeUpload="beforeAvatarUpload"
               :http-request="uploadSuccess"
               :withCredentials="true"
               ref="upload">
      <el-button size="small"
                 type="primary">点击上传</el-button>
      <div slot="tip"
           class="el-upload__tip">只能上传jpg/png文件，且不超过{{size || 500}}kb</div>
    </el-upload>
    <div class="loading-box"
         v-loading="true"
         v-if="loading">
    </div>
    <div v-if="imgArray.length > 0">
      <div class="img-content"
           v-for="(item , index) in imgArray"
           :key="index">
        <img :src="item"
             class="avatar-box">
        <span class="ui-icon  icon-guanbi remove-icon"
              @click="removeImg(index)"></span>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import cookie from "js-cookie";
import { Upload ,Button} from 'element-ui';
export default {
  name: "uploadImg",
   components: {
    [Upload.name]: Upload,
    [Button.name]: Button,
  },
  model: {
    prop: "defImg", // 绑定prop传递的值
    event: "imgUrl" // 定义触发事件名称
  },
  props: ["size", "defImg", "limit"],
  data() {
    return {
      conf: {
        imgUrl: this.$apis.ajaxUrl + "admin/upload/uploadFile.do"
      },
      imgArray: [],
      limitText: 1,
      loading: false
    };
  },
  mounted() {},
  methods: {
    //删除
    removeImg(index) {
      var that = this;
      that.imgArray.splice(index, 1);
      that.$emit("imgUrl", that.imgArray);
      that.$refs['upload'].clearFiles();
    },
    //限制大小
    beforeAvatarUpload(file) {
      var size = 200000000000; // this.size || 500;
      console.log(size);
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isLt2M = file.size / 1024 < size;

      if (!isLt2M) {
        this.$message({
          message: "上传文件大小不能超过 " + size + "kb!",
          type: "warning"
        });
        // return false;
      }
      return isLt2M;
    },
    uploadSuccess(file) {
      var that = this;
      var uploadUrl =that.$apis.ajaxUrl +"api-file/upload?access_token=" +cookie.get("token");
      that.loading = true;
      var fd = new FormData();
      fd.append("file", file.file);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      axios.post(uploadUrl, fd, config)
        .then(res => {
          if (res.status !== 200) {
            that.loading = false;
            Message("网络请求异常！");
          } else {
            switch (res.data.code) {
              case 500:
                that.loading = false;
                return Message("接口错误：" + res.data.msg);
              default:
                if (that.limitText == 1) {
                  that.imgArray = [];
                  that.imgArray.push(res.data.url);
                } else {
                  that.imgArray.push(res.data.url);
                }
                that.$emit("imgUrl", that.imgArray);
                that.$refs['upload'].clearFiles();
                that.loading = false;
                return;
            }
          }
        })
        .catch(res => {});
    }
  },
  watch: {
    defImg: {
      handler(nVal, oVal) {
        if (typeof nVal == "string") {
          this.imgArray = [];
          if (nVal) {
            this.imgArray.push(nVal);
          }
        } else {
          this.imgArray = nVal;
        }
      },
      immediate: true
    },
    limit: {
      handler(nVal, oVal) {
        if (nVal) {
          this.limitText = nVal;
        } else {
          this.limitText = 1;
        }
      },
      immediate: true
    }
  }
};
</script>

<style  scoped>
.img-content {
  position: relative;
  display: inline-block;
  margin-right: 10px;
}
.remove-icon {
  background: #dd001b;
  color: #fff;
  position: absolute;
  top: 0;
  right: 0;
  line-height: 1;
  padding: 5px;
  font-size: 16px;
}
.filebtn {
  opacity: 0;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}

.loading-box {
  display: block;
  width: 100px;
  height: 100px;
}
</style>